#import "MXPullDownMenu.h"
#define kMenuTitleColor [UIColor blackColor]
#define kMenuIndicatorColor GET_HEX_COLOR(CELL_LABLE_BORDER_RED)

@implementation MXPullDownMenu {
    //UIColor *_menuColor;//菜单颜色
    UIView *_backGroundView;//背景视图
    UITableView *_tableView;//下拉表格
    
    NSMutableArray *_titles;//每个菜单数据源
    NSMutableArray *_indicators;//指示器数组
    NSArray *_array;//数据源
    NSInteger _currentSelectedMenudIndex;//菜单选中下标
    bool _show;//是否展示
    NSInteger _numOfMenu;//菜单数量
}

/**
 重写

 @param frame CGRect
 @return self
 */
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

/**
 初始化下拉菜单
 
 @param array 下拉菜单数据源
 @param color 选中颜色
 @return MXPullDownMenu
 */
- (MXPullDownMenu *)initWithArray:(NSArray *)array selectedColor:(UIColor *)color {
    self = [super init];
    if (self) {
        CGSize size = [UIScreen mainScreen].bounds.size;
        self.frame = CGRectMake(0, 0, size.width, 49);
        _isNeedCancleSelected = false;
        //_menuColor = [UIColor blackColor];
        _array = array;
        _numOfMenu = _array.count;
        
        CGFloat textLayerInterval = self.frame.size.width / ( _numOfMenu * 2);
        _titles = [[NSMutableArray alloc] initWithCapacity:_numOfMenu];
        _indicators = [[NSMutableArray alloc] initWithCapacity:_numOfMenu];
        
        for (int i = 0; i < _numOfMenu; i++) {
            CGPoint position = CGPointMake( (i * 2 + 1) * textLayerInterval , self.frame.size.height / 2);
            CATextLayer *title = [self creatTextLayerWithNSString:_array[i][0] withColor:kMenuTitleColor andPosition:position];
//            title.fontSize = 14;
            [self.layer addSublayer:title];
            [_titles addObject:title];
            
            CAShapeLayer *indicator = [self creatIndicatorWithColor:kMenuIndicatorColor andPosition:CGPointMake(position.x + title.bounds.size.width / 2 + 8, self.frame.size.height / 2)];
            [self.layer addSublayer:indicator];
            [_indicators addObject:indicator];
        }
        
        CAShapeLayer *layer = [CAShapeLayer new];
        UIBezierPath *path = [UIBezierPath new];
        [path moveToPoint:CGPointMake(0, 49)];
        [path addLineToPoint:CGPointMake(size.width, 49)];
        layer.path = path.CGPath;
        layer.lineWidth = 0.4;
        layer.strokeColor = [UIColor lightGrayColor].CGColor;
        layer.fillColor = HexRGB(0xEEEFF0).CGColor;
        layer.position = CGPointMake(size.width / 2, 48);
        
        CGPathRef bound = CGPathCreateCopyByStrokingPath(layer.path, nil, layer.lineWidth, kCGLineCapButt, kCGLineJoinMiter, layer.miterLimit);
        layer.bounds = CGPathGetBoundingBox(bound);
        [self.layer addSublayer:layer];
        CGPathRelease(bound);
        
//        layer.position = point;
        
        _tableView = [self creatTableViewAtPosition:CGPointMake(0, self.frame.origin.y + self.frame.size.height)];
        _tableView.tintColor = color;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        
        // 设置menu, 并添加手势
        self.backgroundColor = [UIColor whiteColor];
        UIGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMenu:)];
        [self addGestureRecognizer:tapGesture];
        
        // 创建背景
        _backGroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _backGroundView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
        _backGroundView.opaque = NO;
        UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackGround:)];
        [_backGroundView addGestureRecognizer:gesture];
         
        _currentSelectedMenudIndex = -1;
        _show = NO;
    }
    return self;
}

/**
 处理菜单点击事件

 @param paramSender UITapGestureRecognizer
 */
- (void)tapMenu:(UITapGestureRecognizer *)paramSender {
    CGPoint touchPoint = [paramSender locationInView:self];
    // 得到tapIndex
    NSInteger tapIndex = touchPoint.x / (self.frame.size.width / _numOfMenu);
    for (int i = 0; i < _numOfMenu; i++) {
        if (i != tapIndex) {
            [self animateIndicator:_indicators[i] Forward:NO complete:^{
                [self animateTitle:_titles[i] show:NO complete:^{
                }];
            }];
        }
    }
    
    //如果是点击展开的
    if (tapIndex == _currentSelectedMenudIndex && _show) {
        [self animateIdicator:_indicators[_currentSelectedMenudIndex] background:_backGroundView tableView:_tableView title:_titles[_currentSelectedMenudIndex] forward:NO complecte:^{
            _currentSelectedMenudIndex = tapIndex;
            _show = NO;
            
        }];
    } else {
        //点击未展开的
        _currentSelectedMenudIndex = tapIndex;
        [_tableView reloadData];
        [self animateIdicator:_indicators[tapIndex] background:_backGroundView tableView:_tableView title:_titles[tapIndex] forward:YES complecte:^{
            _show = YES;
        }];
    }
}

/**
 处理背景点击事件

 @param paramSender UITapGestureRecognizer
 */
- (void)tapBackGround:(UITapGestureRecognizer *)paramSender {
    [self animateIdicator:_indicators[_currentSelectedMenudIndex] background:_backGroundView tableView:_tableView title:_titles[_currentSelectedMenudIndex] forward:NO complecte:^{
        _show = NO;
    }];
}


#pragma mark tableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self confiMenuWithSelectRow:indexPath.row];
    [self.delegate PullDownMenu:self didSelectRowAtColumn:_currentSelectedMenudIndex row:indexPath.row];
}

#pragma mark tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_array[_currentSelectedMenudIndex] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.textLabel.font = [UIFont systemFontOfSize:14.0];
    }
    
    [cell.textLabel setTextColor:[UIColor grayColor]];
    [cell setAccessoryType:UITableViewCellAccessoryNone];
    cell.textLabel.text = _array[_currentSelectedMenudIndex][indexPath.row];
    
    if (cell.textLabel.text == [(CATextLayer *)[_titles objectAtIndex:_currentSelectedMenudIndex] string]) {
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
        [cell.textLabel setTextColor:[tableView tintColor]];
    }
    
    return cell;
}

#pragma mark animation

/**
 指示器切换动画

 @param indicator CAShapeLayer
 @param forward BOOL
 @param complete BLOCK
 */
- (void)animateIndicator:(CAShapeLayer *)indicator Forward:(BOOL)forward complete:(void(^)())complete
{
    [CATransaction begin];
    [CATransaction setAnimationDuration:0.25];
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithControlPoints:0.4 :0.0 :0.2 :1.0]];
    
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    anim.values = forward ? @[ @0, @(M_PI) ] : @[ @(M_PI), @0 ];
    
    if (!anim.removedOnCompletion) {
        [indicator addAnimation:anim forKey:anim.keyPath];
    } else {
        [indicator addAnimation:anim andValue:anim.values.lastObject forKeyPath:anim.keyPath];
    }
    
    [CATransaction commit];
    
    indicator.strokeColor = forward ? _tableView.tintColor.CGColor : kMenuIndicatorColor.CGColor;
//    indicator.fillColor = forward ? _tableView.tintColor.CGColor : _menuColor.CGColor;
    
    complete();
}

/**
 背景遮盖切换动画

 @param view UIView
 @param show BOOL
 @param complete BLOCK
 */
- (void)animateBackGroundView:(UIView *)view show:(BOOL)show complete:(void(^)())complete {
    if (show) {
        [self.superview addSubview:view];
        [view.superview addSubview:self];

        [UIView animateWithDuration:0.2 animations:^{
            view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.3];
        }];
    } else {
        [UIView animateWithDuration:0.2 animations:^{
            view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
        } completion:^(BOOL finished) {
            [view removeFromSuperview];
        }];
        
    }
    complete();
}

/**
 表显示和隐藏动画

 @param tableView UITableView
 @param show BOOL
 @param complete BLOCK
 */
- (void)animateTableView:(UITableView *)tableView show:(BOOL)show complete:(void(^)())complete {
    if (show) {
        tableView.frame = CGRectMake(0, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 0);
        [self.superview addSubview:tableView];
        
        CGFloat tableViewHeight = ([tableView numberOfRowsInSection:0] > 7) ? (7 * tableView.rowHeight + 20) : ([tableView numberOfRowsInSection:0] * tableView.rowHeight);
        
        [UIView animateWithDuration:0.2 animations:^{
            _tableView.frame = CGRectMake(0, self.frame.origin.y + self.frame.size.height, self.frame.size.width, tableViewHeight);
        }];
    } else {
        [UIView animateWithDuration:0.2 animations:^{
            _tableView.frame = CGRectMake(0, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 0);
        } completion:^(BOOL finished) {
            [tableView removeFromSuperview];
        }];
    }
    
    complete();
}

/**
 CATextLayer动画

 @param title CATextLayer
 @param show BOOL
 @param complete BLOCK
 */
- (void)animateTitle:(CATextLayer *)title show:(BOOL)show complete:(void(^)())complete {
    if (show) {
        title.foregroundColor = _tableView.tintColor.CGColor;
    } else {
        title.foregroundColor = kMenuTitleColor.CGColor;
    }
    CGSize size = [self calculateTitleSizeWithString:title.string];
    CGFloat sizeWidth = (size.width < (self.frame.size.width / _numOfMenu) - 25) ? size.width : self.frame.size.width / _numOfMenu - 25;
    title.bounds = CGRectMake(0, 0, sizeWidth, size.height);

    complete();
}

/**
 整个选中动画

 @param indicator CAShapeLayer
 @param background UIView
 @param tableView UITableView
 @param title CATextLayer
 @param forward BOOL
 @param complete BLOCK
 */
- (void)animateIdicator:(CAShapeLayer *)indicator background:(UIView *)background tableView:(UITableView *)tableView title:(CATextLayer *)title forward:(BOOL)forward complecte:(void(^)())complete{
    [self animateIndicator:indicator Forward:forward complete:^{
        [self animateTitle:title show:forward complete:^{
            [self animateBackGroundView:background show:forward complete:^{
                [self animateTableView:tableView show:forward complete:^{
                }];
            }];
        }];
    }];
    
    complete();
}


#pragma mark drawing
/**
 创建CAShapeLayer Indicator

 @param color UIColor
 @param point CGPoint
 @return CAShapeLayer
 */
- (CAShapeLayer *)creatIndicatorWithColor:(UIColor *)color andPosition:(CGPoint)point {
    CAShapeLayer *layer = [CAShapeLayer new];
    
    UIBezierPath *path = [UIBezierPath new];
    [path moveToPoint:CGPointMake(5.8, 6.3)];
//    [path addLineToPoint:CGPointMake(8, 0)];
    [path addLineToPoint:CGPointMake(11, 12.6)];
    [path addLineToPoint:CGPointMake(16.1, 6.3)];
//    [path closePath];
    
//    layer.fillMode
    layer.path = path.CGPath;
    layer.lineWidth = 1.0;
    layer.strokeColor = color.CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    
    CGPathRef bound = CGPathCreateCopyByStrokingPath(layer.path, nil, layer.lineWidth, kCGLineCapButt, kCGLineJoinMiter, layer.miterLimit);
    layer.bounds = CGPathGetBoundingBox(bound);
    CGPathRelease(bound);
    layer.position = point;
    
    return layer;
}

/**
 创建CAShapeLayer SeparatorLine

 @param color UIColor
 @param point CGPoint
 @return CAShapeLayer
 */
- (CAShapeLayer *)creatSeparatorLineWithColor:(UIColor *)color andPosition:(CGPoint)point{
    CAShapeLayer *layer = [CAShapeLayer new];
    
    UIBezierPath *path = [UIBezierPath new];
    [path moveToPoint:CGPointMake(160,0)];
    [path addLineToPoint:CGPointMake(160, 20)];
    
    layer.path = path.CGPath;
    layer.lineWidth = 1.0;
    layer.strokeColor = color.CGColor;
    
    CGPathRef bound = CGPathCreateCopyByStrokingPath(layer.path, nil, layer.lineWidth, kCGLineCapButt, kCGLineJoinMiter, layer.miterLimit);
    layer.bounds = CGPathGetBoundingBox(bound);
    CGPathRelease(bound);
    layer.position = point;
    
    return layer;
}

/**
 创建CATextLayer

 @param string NSString
 @param color UIColor
 @param point CGPoint
 @return CATextLayer
 */
- (CATextLayer *)creatTextLayerWithNSString:(NSString *)string withColor:(UIColor *)color andPosition:(CGPoint)point {
    CGSize size = [self calculateTitleSizeWithString:string];
    CATextLayer *layer = [CATextLayer new];
    CGFloat sizeWidth = (size.width < (self.frame.size.width / _numOfMenu)) ? size.width : self.frame.size.width / _numOfMenu;
    layer.bounds = CGRectMake(0, 0, sizeWidth, size.height);
    layer.string = string;
    layer.fontSize = 15.0;
    layer.alignmentMode = kCAAlignmentCenter;
    layer.foregroundColor = color.CGColor;
    
    layer.contentsScale = [[UIScreen mainScreen] scale];
    
    layer.position = point;
    
    return layer;
}

/**
 通过位置创建表格

 @param point CGPoint
 @return UITableView
 */
- (UITableView *)creatTableViewAtPosition:(CGPoint)point {
    UITableView *tableView = [UITableView new];
    tableView.frame = CGRectMake(point.x, point.y, self.frame.size.width, 0);
    tableView.rowHeight = 44;
    
    return tableView;
}


#pragma mark otherMethods

/**
 计算标题长度

 @param string NSString
 @return CGSize
 */
- (CGSize)calculateTitleSizeWithString:(NSString *)string {
    CGFloat fontSize = 15.0;
    NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]};
    CGSize size = [string boundingRectWithSize:CGSizeMake(280, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    return size;
}

/**
 配置菜单选中的行

 @param row NSInteger
 */
- (void)confiMenuWithSelectRow:(NSInteger)row {
    //判断菜单只能选中某一个
    if (self.isNeedCancleSelected){
        int i = 0;
        for (CATextLayer *tit in _titles){
            //重新调整位置
            if (i != _currentSelectedMenudIndex) {
                tit.string = [[_array objectAtIndex:i] objectAtIndex:0];
                CAShapeLayer *indicator = (CAShapeLayer *)_indicators[i];
                
                CGSize size = [self calculateTitleSizeWithString:tit.string];
                CGFloat sizeWidth = (size.width < (self.frame.size.width / _numOfMenu) - 25) ? size.width : self.frame.size.width / _numOfMenu - 25;
                tit.bounds = CGRectMake(0, 0, sizeWidth, size.height);
                
                indicator.position = CGPointMake(tit.position.x + tit.frame.size.width / 2 + 8, indicator.position.y);
            }
            
            i ++;
        }
    }
    
    CATextLayer *title = (CATextLayer *)_titles[_currentSelectedMenudIndex];
    title.string = [[_array objectAtIndex:_currentSelectedMenudIndex] objectAtIndex:row];
    
    [self animateIdicator:_indicators[_currentSelectedMenudIndex] background:_backGroundView tableView:_tableView title:_titles[_currentSelectedMenudIndex] forward:NO complecte:^{
        _show = NO;
    }];
    
    CAShapeLayer *indicator = (CAShapeLayer *)_indicators[_currentSelectedMenudIndex];
    indicator.position = CGPointMake(title.position.x + title.frame.size.width / 2 + 8, indicator.position.y);
}

/**
 重置菜单
 */
- (void)reSetTitle {
    int i = 0;
    for (CATextLayer *tit in _titles){
        tit.string = [[_array objectAtIndex:i] objectAtIndex:0];
        
        CAShapeLayer *indicator = (CAShapeLayer *)_indicators[i];
        CGSize size = [self calculateTitleSizeWithString:tit.string];
        CGFloat sizeWidth = (size.width < (self.frame.size.width / _numOfMenu) - 25) ? size.width : self.frame.size.width / _numOfMenu - 25;
        tit.bounds = CGRectMake(0, 0, sizeWidth, size.height);
        indicator.position = CGPointMake(tit.position.x + tit.frame.size.width / 2 + 8, indicator.position.y);
        
        i ++;
    }
}

@end

#pragma mark - CALayer Category
@implementation CALayer (MXAddAnimationAndValue)

- (void)addAnimation:(CAAnimation *)anim andValue:(NSValue *)value forKeyPath:(NSString *)keyPath {
    [self addAnimation:anim forKey:keyPath];
    [self setValue:value forKeyPath:keyPath];
}

@end
